<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>权限管理</title>
    <script src="../js/axios-0.18.0.js"></script>
    <script src="../js/axios-interceptors.js"></script>
    <script src="../js/vue3.js"></script>
    <script src="../js/element-plus.js"></script>
    <script src="../js/icons-vue.js"></script>
    <script src="../js/zh-cn.js"></script>
    <link href="../css/index.css" rel="stylesheet"/>
    <style>
        body {
            margin: 0;
            padding: 20px;
            font-family: "Helvetica Neue", Arial, sans-serif;
            background: #f4f6f9;
        }

        .btn-container {
            margin-bottom: 16px;
        }

        .table-container {
            background: #fff;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
        }

        .pagination-container {
            margin-top: 15px;
            display: flex;
            justify-content: flex-end;
        }

        /* 按钮样式优化 */
        .el-button {
            border-radius: 4px;
            transition: all 0.3s ease;
        }
        .el-button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        .el-button--primary {
            background-color: #409eff;
            border-color: #409eff;
        }
        .el-button--danger {
            background-color: #f56c6c;
            border-color: #f56c6c;
        }

        /* 表格样式优化 */
        .el-table {
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 按钮区 -->
    <div class="btn-container">
        <el-upload
                v-model:file-list="fileList"
                class="upload-demo"
                action="/permission/upload"
                :on-success="handleUploadSuccess"
                :befor-upload="beforeExcelUpload"
                :on-error="handleUploadError"
                :limit="1"
        >
            <el-button type="primary" >模板文件上传</el-button>
        </el-upload>
        <el-button type="primary" @click="getPermModel">模板文件下载</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
        <el-table :data="tableData" border stripe style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="编号" width="80"></el-table-column>
            <el-table-column prop="parentId" label="父ID" width="80"></el-table-column>
            <el-table-column prop="pname" label="权限名称" width="150"></el-table-column>
            <el-table-column prop="url" label="URL" width="180"></el-table-column>
            <el-table-column prop="code" label="权限编码" width="150"></el-table-column>
            <el-table-column prop="level" label="权限等级" width="100"></el-table-column>
            <el-table-column prop="sort" label="权限等级排序" width="80"></el-table-column>
            <el-table-column label="操作" width="160">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="pagination-container">
            <el-pagination
                    :background="true"
                    :total="total"
                    :page-sizes="[5, 10, 15]"
                    layout="total, sizes, prev, pager, next, jumper"
                    v-model:page-size="pageSize"
                    v-model:current-page="pageNum"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"></el-pagination>
        </div>
    </div>

    <!-- 编辑权限弹窗 -->
    <el-dialog title="编辑权限"
               v-model="editDialogVisible"
               @close="clearValid"
               width="500px">
        <el-form :model="editForm"
                 ref="permissionFormRef"
                 :rules="rules"
                 label-width="100px">
            <el-form-item label="编号" prop="id">
                <el-input v-model="editForm.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="父ID" prop="parentId">
                <el-input v-model="editForm.parentId"></el-input>
            </el-form-item>
            <el-form-item label="权限名称" prop="pname">
                <el-input v-model="editForm.pname"></el-input>
            </el-form-item>
            <el-form-item label="URL" prop="url">
                <el-input v-model="editForm.url"></el-input>
            </el-form-item>
            <el-form-item label="权限编码" prop="code">
                <el-input v-model="editForm.code"></el-input>
            </el-form-item>
            <el-form-item label="权限等级" prop="level">
                <el-input v-model="editForm.level"></el-input>
            </el-form-item>
            <el-form-item label="权限等级排序" prop="sort">
                <el-input v-model="editForm.sort"></el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="handleEditSubmit">提交</el-button>
            </span>
        </template>
    </el-dialog>
</div>

<script>
    const {createApp, ref, onMounted} = Vue;
    const {ElMessage, ElDialog, ElForm, ElFormItem, ElInput,ElMessageBox} = ElementPlus;
    const app = createApp({
        setup() {
            // 表格数据（权限列表）
            const tableData = ref([]);
            // 分页参数
            const total = ref(0);
            const pageSize = ref(5);
            const pageNum = ref(1);


            // 编辑弹窗显隐控制
            const editDialogVisible = ref(false);
            // 编辑表单数据
            const editForm = ref({
                id: '',
                parentId: '',
                pname: '',
                url: '',
                code: '',
                level: '',
                sort: ''
            });


            // 加载权限数据
            const getPermission = () => {
                axios.get(`/permission/${pageNum.value}/${pageSize.value}`)
                    .then(resp => {
                        tableData.value = resp.data.obj.data;
                        total.value = resp.data.obj.total;
                    })
                    .catch((error) => {
                        ElMessage.error(error.response.data.msg);
                    });
            };

            // 定义响应式的文件列表
            const fileList = ref([]);

            // 模板上传
            const handleUploadSuccess = (resp, file, uploadFileList) => {
                console.log(resp)
                if (resp.code === 200) {
                    ElMessage.success(resp.msg);
                    fileList.value = [];
                    getPermission();
                }else {
                    ElMessage.error(resp.msg);
                }
            };
            //上传模板验证
            const beforeExcelUpload= (rawFile) => {
                const allowedTypes = [
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
                    'application/vnd.ms-excel' // .xls
                ];

                if (!allowedTypes.includes(rawFile.type)) {
                    ElMessage.error('您上传的文件必须是Excel格式（.xlsx或.xls）')
                    return false
                } else if (rawFile.size / 1024 / 1024 > 2) {
                    ElMessage.error('您的文件最大不能超过2MB!')
                    return false
                }
                return true
            }

            //下载模板(使用fetch)
            const getPermModel = async (fileName) => {
                fileName = "perms_model.xlsx";
                try {
                    //发起了一个 HTTP 请求去获取文件数据
                    const response = await fetch(`/permission/downloadPermModel/perms_model.xlsx`, {
                        method: 'GET',
                    });

                    if (response.ok) {
                        // 获取自定义响应头
                        const message = response.headers.get('X-Download-Message') || '下载成功';
                        const filename = response.headers.get('X-Download-Filename') || fileName;

                        // 创建下载链接
                        const blob = await response.blob();
                        const url = window.URL.createObjectURL(blob);
                        const link = document.createElement('a');
                        link.href = url;
                        link.download = filename;
                        document.body.appendChild(link);
                        //模拟用户点击这个 <a> 标签
                        link.click();
                        //释放内存
                        link.remove();
                        window.URL.revokeObjectURL(url);

                        ElMessage.success(message);
                    } else {
                        const errorData = await response.json();
                        ElMessage.error(errorData.message || '下载失败');
                    }
                } catch (error) {
                    ElMessage.error('下载失败: ' + error.message);
                }
            };

            // 编辑摁钮
            const handleEdit = (row) => {
                editForm.value = {...row};
                editDialogVisible.value = true;
            };

            // 提交编辑
            const handleEditSubmit = () => {
                permissionFormRef.value.validate((valid) => {
                    if (valid) {
                        if (!permissionFormRef.value.id) {
                            axios.put(`/permission/updatePermission`, editForm.value).then(resp=>{
                                if (resp.data.code === 200) {
                                    ElMessage.success(resp.data.msg);
                                }
                                getPermission();
                                editDialogVisible.value = false;
                            })
                        }
                    }
                });
            };

            //弹窗表单引用
            const permissionFormRef= ref(null);
            // 清空校验红字信息
            const clearValid = () => {
                if (permissionFormRef.value) {
                    permissionFormRef.value.resetFields();
                }
            }
            //编辑弹窗的取消方法
            const closeDialog = () => {
                clearValid();
                editDialogVisible.value = false;
            }


            // 删除权限（空方法，保留结构）
            const handleDelete = (row) => {
                ElMessageBox.confirm('将永久删除该电影信息. 确定?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                })
                    .then(() => {
                        axios.delete(`/permission/deletePermission/${row.id}`).then(resp=>{
                            if(resp.data.code===200){
                                ElMessage.success(resp.data.msg);
                                getPermission();
                            }
                        }).catch(error=>{
                            ElMessage.error(error.response.data.msg);
                        })
                    })
            };



            // 分页
            const handleSizeChange = (val) => {
                pageSize.value = val;
                getPermission();
            };
            const handlePageChange = (val) => {
                pageNum.value = val;
                getPermission();
            };

            // 表单验证规则
            const rules = ref({
                id: [
                    { required: true, message: '编号不能为空', trigger: 'blur' }
                ],
                parentId: [
                    { required: true, message: '父ID不能为空', trigger: 'blur' }
                ],
                pname: [
                    { required: true, message: '权限名称不能为空', trigger: 'blur' }
                ],
                url: [
                    { required: true, message: 'URL不能为空', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '权限编码不能为空', trigger: 'blur' }
                ],
                level: [
                    { required: true, message: '权限等级不能为空', trigger: 'blur' }
                ],
                sort: [
                    { required: true, message: '权限等级排序不能为空', trigger: 'blur' }
                ]
            });

            // 页面加载时获取数据
            onMounted(() => {
                getPermission();
            });

            return {
                tableData,
                total,
                pageSize,
                pageNum,
                editDialogVisible,
                editForm,
                rules,
                permissionFormRef,
                fileList,
                clearValid,
                handleUploadSuccess,
                handleEdit,
                handleEditSubmit,
                handleDelete,
                handleSizeChange,
                handlePageChange,
                closeDialog,
                getPermission,
                beforeExcelUpload,
                getPermModel,
            };
        }
    });
    app.use(ElementPlus, {
        locale: ElementPlusLocaleZhCn
    });
    // 注册 Element Plus 图标
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component);
    }
    app.mount("#app");
</script>
</body>
</html>